var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var documentRouter = require('./routes/document');
var categorytRouter = require('./routes/category');
var toolstRouter = require('./routes/tools');

var app = express();

//解决跨域
app.all('*', (req, res, next) => {
  // 设置响应头,解决跨域
  res.header('Access-Control-Allow-Origin', '*'); //允许所有域名访问
  res.header('Access-Control-Allow-Headers', '*'); //允许访问的请求头
  res.header('Access-Control-Allow-Methods', '*'); //允许访问的请求方法
  next() //放行 
})



const {expressjwt}  = require('express-jwt')

const SECRET_KEY = 'login2025' // 与生成token的密钥要一致!

// 1. 使用中间件解析token
// 2. 使用 .unless 排除无需校验的路由(比如: 登录)
app.use(
  expressjwt ({
      secret: SECRET_KEY,
      algorithms: ['HS256'], // 使用何种加密算法解析
  })
    .unless({ path: [ '/api/login', '/public',/^\/images\//, '/ai/visit', '/ai/visit/stats', '/ai/visit/summary'] }) // 登录页和访问统计接口无需校验
);



// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/api', indexRouter);
app.use('/users', usersRouter);
app.use('/doc', documentRouter);
app.use('/cate', categorytRouter);
app.use('/ai', toolstRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// JWT错误处理
app.use(function(err, req, res, next) {
  console.log(err,'err...');
  if (err.name === 'TokenExpiredError') {
    return res.status(401).json({
      code: 401,
      msg: 'token已过期,请重新登录',
      data: null
    });
  }
  
  if (err.name === 'JsonWebTokenError') {
    return res.status(401).json({
      code: 401,
      msg: '无效的toke,请重新登录',
      data: null
    });
  }
  
  next(err);
});


// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});


module.exports = app;
